package com.dzwww.recommend.rule.service.common;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;

/**
 * 对接新华智云推荐api接口
 * @author Administrator
 * 2019年7月24日
 */
@Slf4j
public class ShuWenInterfaceImpl {
	
	private static String BASE_URL = "http://api.xinwen.cn";
	private static String RECOMMEND_URL = "/recservice/personal";
	private static String RELATIVE_URL = "/recservice/relative";
	private static String HOT_URL = "/recservice/hot";
	
    private static String ACCESS_KEY = "Pcq5n2jiDRFcTxTq";
    private static String SECRET_KEY = "6a795fbd76014a8b8373893dd960d83d";
    private static String ORG_ID = "zm5144";
    private static String INSTANCE = "hb_news";
	

	/**
	 * 个性化推荐
	 * @param userId
	 * @param size
	 * @return
	 */
	public static String recommend(String userId, int size){
		String url = getUrl(RECOMMEND_URL);
		JsonObject jo = new JsonObject();
		jo.addProperty("size", size);
		jo.addProperty("org_id", ORG_ID);
		jo.addProperty("instance", INSTANCE);
		jo.addProperty("user_id", userId);
		String result = getResponse(url, HttpMethod.POST, jo.toString());
		log.info("------recommend-----: " + result);
		return result;
	}
	
	/**
	 * 相关新闻推荐
	 * @param userId
	 * @param newsId
	 * @param size
	 * @return
	 */
	public static String relative(String userId, String newsId, int size){
		String url = getUrl(RELATIVE_URL);
		JsonObject jo = new JsonObject();
		jo.addProperty("size", size);
		jo.addProperty("org_id", ORG_ID);
		jo.addProperty("instance", INSTANCE);
		jo.addProperty("user_id", userId);
		jo.addProperty("news_id", newsId);
		String result = getResponse(url, HttpMethod.POST, jo.toString());
		log.info("------relative-----: " + result);
		return result;
	}
	
	/**
	 * 热门新闻推荐
	 * @param userId
	 * @param size
	 * @return
	 */
	public static String hot(String userId, int size){
		String url = getUrl(HOT_URL);
		JsonObject jo = new JsonObject();
		jo.addProperty("size", size);
		jo.addProperty("org_id", ORG_ID);
		jo.addProperty("instance", INSTANCE);
		jo.addProperty("user_id", userId);
		String result = getResponse(url, HttpMethod.POST, jo.toString());
		log.info("------hot-----: " + result);
		return result;
	}
	
	private static String getResponse(String url, HttpMethod method, String requestBody){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		HttpEntity<String> httpEntity = new HttpEntity<String>(requestBody, headers);
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, httpEntity, String.class);
		return responseEntity.getBody();
	}
	
	private static String signString(String accessKey, String accessSecret, long timestamp) throws InvalidKeyException, IllegalStateException {
	    try {
	        String content = accessSecret + timestamp + accessKey;
	        MessageDigest md5 = MessageDigest.getInstance("MD5");
	        md5.update(content.getBytes("utf-8"));
	        byte[] summery = md5.digest();
	        StringBuffer md5StrBuff = new StringBuffer();
	        for (int i = 0; i < summery.length; i++) {
	            if (Integer.toHexString(0xFF & summery[i]).length() == 1) {
	                md5StrBuff.append("0").append(
	                        Integer.toHexString(0xFF & summery[i]));
	            } else {
	                md5StrBuff.append(Integer.toHexString(0xFF & summery[i]));
	            }
	        }
	        return md5StrBuff.toString();
	    } catch (NoSuchAlgorithmException e) {
	        throw new RuntimeException("MD5 not supported.");
	    } catch (UnsupportedEncodingException e) {
	        throw new RuntimeException("UTF-8 not supported.");
	    }
	} 
	
	private static String getUrl(String urlType){
		String url = "";
		long timestamp = System.currentTimeMillis();
		try {
			String signString = signString(ACCESS_KEY, SECRET_KEY, timestamp);
			url = BASE_URL + urlType + "?access_key=" + ACCESS_KEY + "&timestamp=" + timestamp + "&signature=" + signString;
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		return url;
	}
	
	public static void main(String[] args) {
//		ShuWenInterfaceImpl.recommend("864447034975951", 10);
		ShuWenInterfaceImpl.relative("864447034975951", "2075497", 10);
//		ShuWenInterfaceImpl.hot("864447034975951", 10);
	}
    
}